'use client';

import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { EbbinghausPage } from './EbbinghausPage';
import { useHash } from './useHash';

export type AllInOneData = {
  tags: {
    name: string;
    title: string;
    subtitle: string;
  }[];
  data: {
    tag: string[];
    content: string;
  }[];
};

export function FilterableEbbinghausPage({ tags, data }: AllInOneData) {
  const hash = useHash();

  const [selectedKey, setSelectedKey] = useState('all');

  const filtered = useMemo(() => {
    let temp = data;
    if (selectedKey !== 'all') {
      temp = data.filter((x) => x.tag.includes(selectedKey));
    }
    return temp.map((x) => x.content);
  }, [selectedKey, data]);

  const { title, subtitle } = useMemo(
    () => tags.find((x) => x.name === selectedKey) || { title: '', subtitle: '' },
    [selectedKey, tags]
  );

  useEffect(() => {
    if (hash) {
      setSelectedKey(hash.substring(2));
    }
  }, [hash]);

  // console.log({ tags, data, selectedKey, filtered, title, subtitle });
  return (
    <>
      <nav className='noprint'>
        <div className='p-5 flex-row gap-20' style={{ display: 'flex', flexDirection: 'row', gap: 20 }}>
          {tags.map((x, i) => (
            <Link key={i} href={`#/${x.name}`} onClick={() => setSelectedKey(x.name)}>
              {x.title}
            </Link>
          ))}
        </div>
      </nav>

      <main>
        <EbbinghausPage title={title} subtitle={subtitle} data={filtered} />
      </main>
    </>
  );
}
